<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Cache;
use think\Db;

/**
 * 业务管理
 *
 * @icon fa fa-circle-o
 */
class Business extends Backend
{

    /**
     * Business模型对象
     * @var \app\admin\model\Business
     */
    protected $model = null;
    protected $rulelist;

    protected $modelValidate = true;

    private $contract = [
        3 => '3月',
        6 => '6月',
        12 => '1年',
        24 => '2年',
        36 => '3年'
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Business;
        $ruleList = Db::name("business")->order('id ASC')->select();
        foreach ($ruleList as $k => &$v) {
            $v['name'] = __($v['name']);
        }
        unset($v);
        Tree::instance()->init($ruleList)->icon = ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'];
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
            unset($v['spacer']);
        }
        unset($v);

        $this->view->assign('ruledata', $ruledata);
        $this->view->assign('ruledataList', json_encode($this->rulelist, true));
        $this->view->assign("menutypeList", $this->model->getMenutypeList());
        $this->view->assign("contractList", $this->contract);
        $this->assignconfig("contractList", $this->contract);

    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = $this->rulelist;
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                $result = $this->model->validate()->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                Cache::rm('__menu__');
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $haschild = 1;
            foreach ($this->rulelist as $val) {
                if ($ids == $val['id']) {
                    $haschild = $val['haschild'];
                }
            }
            $row = $row->getData();
            $row['haschild'] = $haschild;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
